import { defineStore } from 'pinia'
import { dailyRecordApi } from '@/api'

export const useHealthStore = defineStore('health', {
  state: () => ({
    dailyRecords: [],
    currentRecord: null,
    loading: false
  }),
  
  getters: {
    // 获取最近的健康记录
    recentRecords: (state) => {
      return state.dailyRecords.slice(0, 10)
    },
    
    // 获取BMI趋势
    bmiTrend: (state) => {
      return state.dailyRecords
        .filter(record => record.bmi)
        .map(record => ({
          date: record.recordDate,
          bmi: record.bmi
        }))
    }
  },

  actions: {
    // 保存健康记录
    async saveRecord(recordData) {
      this.loading = true
      try {
        const response = await dailyRecordApi.saveRecord(recordData)
        this.dailyRecords.unshift(response)
        this.currentRecord = response
        return response
      } catch (error) {
        console.error('保存健康记录失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取某日期的健康记录
    async getRecord(date) {
      this.loading = true
      try {
        const response = await dailyRecordApi.getRecord(date)
        this.currentRecord = response
        return response
      } catch (error) {
        console.error('获取健康记录失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取日期范围内的健康记录
    async getRecordsByDateRange(startDate, endDate) {
      this.loading = true
      try {
        const response = await dailyRecordApi.getRecords(startDate, endDate)
        this.dailyRecords = response
        return response
      } catch (error) {
        console.error('获取健康记录失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取最近的健康记录
    async getRecentRecords(limit = 10) {
      this.loading = true
      try {
        const response = await dailyRecordApi.getRecentRecords(limit)
        this.dailyRecords = response
        return response
      } catch (error) {
        console.error('获取健康记录失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除健康记录
    async deleteRecord(recordId) {
      this.loading = true
      try {
        await dailyRecordApi.deleteRecord(recordId)
        // 从本地状态中移除
        this.dailyRecords = this.dailyRecords.filter(record => record.recordId !== recordId)
        if (this.currentRecord && this.currentRecord.recordId === recordId) {
          this.currentRecord = null
        }
      } catch (error) {
        console.error('删除健康记录失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 清空当前记录
    clearCurrentRecord() {
      this.currentRecord = null
    }
  }
})